import { API_TIME_OUT, AUTH_TOKEN_NAME, GLOBAL_PATH_FIX } from '@/config';
import { HttpResponse, HttpResponseContent } from '@/interface/common';
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import router from '@/router';
import { getMessage } from './status';
import { clearAuthToken, clearPermissions } from '@/utils/auth';
import { showLoading, hideLoading } from '@/utils/loading';

const baseURL =
  import.meta.env.MODE !== 'development'
    ? `${(import.meta.env.VITE_BASE_URL as string) || ''}${GLOBAL_PATH_FIX}`
    : GLOBAL_PATH_FIX;

const axiosInstance: AxiosInstance = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
  timeout: API_TIME_OUT,
});

// axios实例拦截请求
axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig): AxiosRequestConfig => {
    if (config.headers && (!config.headers.hideLoading as boolean)) {
      showLoading();
    }
    const auth_token = localStorage.getItem(AUTH_TOKEN_NAME);
    if (auth_token) {
      config.headers = {
        ...config.headers,
        Authorization: auth_token,
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// axios实例拦截响应
axiosInstance.interceptors.response.use(
  async (response: AxiosResponse): Promise<HttpResponse | Blob> => {
    hideLoading();
    if (response.config.responseType == 'blob') {
      return Promise.resolve(response.data);
    }
    const res: HttpResponseContent = response.data;
    if (res.code === 200) {
      return Promise.resolve(res.data as HttpResponse);
    } else if (res.code === 301) {
      router.push('/extract/CodePage');
      return Promise.reject(res);
    } else if (res.code === 401) {
      ElMessage.error(res.msg);
      clearPermissions();
      clearAuthToken();
      router.replace('/login');
      return Promise.reject(res);
    } else {
      ElMessage({
        message: res.msg || getMessage(res.code),
        type: 'error',
        duration: 1000,
      });
      return Promise.reject(res);
    }
  },
  (error) => {
    hideLoading();
    const { response } = error;
    if (response) {
      ElMessage({
        message: getMessage(response.status),
        type: 'error',
        duration: 1000,
      });
      return Promise.reject(response.data);
    } else {
      ElMessage({
        message: '网络连接异常,请稍后再试!',
        type: 'error',
        duration: 1000,
      });
    }
  }
);

export { axiosInstance };
